package com.itheima.controller;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/*上传下载*/
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;


    /**
     * <p>Description: 上传文件</p>
     *
     * @author liuyiming
     * @date 2022-10-09 16:49
     * @version 1.0.0
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info("上传文件{}",file.toString());
        //截取上传图片的后缀名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID生成新的文件名称，以防止文件名称相同覆盖文件的情况
        String filePath = "/"+UUID.randomUUID().toString() + suffix;
        //使用时间来创建文件夹，以防止文件夹中存储太多图片，而回显的时候查询时间较长
        String date = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        File dir = new File(basePath + date);
        dir.mkdirs();

        try {
            //将文件存到指定位置
            file.transferTo(new File(dir+filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //   2020/10/10/8558a9f3-01d3-421e-af16-e2b1060d5a7b.png
        return R.success(date+filePath);
    }

    /**
     * <p>Description: 下载文件</p>
     *
     * @author liuyiming
     * @date 2022-10-09 21:12
     * @version 1.0.0
     */
    @GetMapping("/download")
    public void dowmload(String name, HttpServletResponse response) {
        try {
            // D:/img/       2022/10/10/8558a9f3-01d3-421e-af16-e2b1060d5a7b.png
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));

            //输出流，通过输出流将文件写回浏览器，在浏览器中展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            //设置图片格式
            response.setContentType("image/jpeg");
            //开始写回浏览器
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
